package initialize

import (
	"io/ioutil"
	"log"

	"github.com/batchcorp/rabbit"
	redis "github.com/go-redis/redis/v9"
	yaml "gopkg.in/yaml.v2"
)

// load
type Configure struct {
	filepath  string
	Opt       Option
	Opts      *Options
	Log       *Logs
	RedisMgr  *RedisClientMgr
	RabbitMgr *RabbitClientMgr
}

var (
	Cfg *Configure
)

func NewConfigure(filepath string) *Configure {
	return &Configure{
		filepath: filepath,
	}
}

// load-cfg-file
func (c *Configure) initCfg() {

	c.Opts = &Options{}
	c.Log = &Logs{}
	c.RedisMgr = &RedisClientMgr{Clients: make(map[int]*redis.Client)}
	c.RabbitMgr = &RabbitClientMgr{Clients: make(map[string]*rabbit.Rabbit)}
}

// load-opt
func (c *Configure) loadOpts() {

	file, err := ioutil.ReadFile(c.filepath)
	if err != nil {
		log.Printf("[conf] Description Failed to read the configuration file #%v", err)
	}

	err = yaml.Unmarshal(file, c.Opts)

	if err != nil {
		log.Fatalf("[conf] Parse failure: %v", err)
	}
	c.Opt = c.Opts.GetEnv()

}

// load-redis
func (c *Configure) loadRedis() {
	c.RedisMgr.Init(c.Opt)
}

// load-redis
func (c *Configure) loadLog() {
	c.Log.Init(c.Opt)
}

// load-redis
func (c *Configure) loadRabbit() {
	c.RabbitMgr.Init(c.Opt)
}

// load-all
func (c *Configure) Load() {

	c.initCfg()    // init
	c.loadOpts()   // load config
	c.loadLog()    // init log
	c.loadRedis()  // init redis
	c.loadRabbit() // init rabbit
}
